package handler

import (
	"chat/pkg"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"strconv"
	"sync"
)

type Message struct {
	UserId string `json:"user_id" form:"user_id"`
	SendId string `json:"send_id" form:"send_id"`
}
type Nodes struct {
	Conn *websocket.Conn
	Data chan []byte
}

var clinesMap map[string]*Nodes = make(map[string]*Nodes, 0)
var wsg sync.WaitGroup

func Demo(c *gin.Context) {
	var chat Message
	c.ShouldBind(&chat)
	id := chat.UserId
	send_id := chat.SendId
	upgrader := websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}
	var msg = &Message{
		UserId: id,
		SendId: send_id,
	}
	conn, _ := upgrader.Upgrade(c.Writer, c.Request, nil)
	var nodes = &Nodes{
		Conn: conn,
		Data: make(chan []byte, 100),
	}
	clinesMap[id+"_"+send_id] = nodes
	wsg.Add(4)
	go SeoverWrtiter(nodes, msg)
	go SeoverReveerm(nodes, msg)
	wsg.Wait()
}

func SeoverWrtiter(nodes *Nodes, msg *Message) {
	defer wsg.Done()
	for {
		select {
		case data := <-nodes.Data:
			res := pkg.Chect(string(data))
			if res {
				atoi, _ := strconv.Atoi(msg.UserId)
				if atoi == 10 {
					nodes.Conn.WriteMessage(websocket.TextMessage, []byte("此账号多次发送违规语言已被封禁"))
				} else {
					err := nodes.Conn.WriteMessage(websocket.TextMessage, data)
					if err != nil {
						log.Println("消息发送失败")
					}
				}
			} else {
				log.Println("消息不合规，请重新发送")
			}

		}
	}
}

func SeoverReveerm(node *Nodes, msg *Message) {
	for {
		_, message, _ := node.Conn.ReadMessage()
		Reveerm, err := clinesMap[msg.SendId+"_"+msg.UserId]
		if err {
			Reveerm.Data <- message
		}
	}
}
